<!-- src/views/stocktaking/list.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { getInfoPageApi, confirmApi, deleteInfoApi } from '@/api/stocktaking/stocktakingInfo.js'
import { getUserListApi } from '@/api/user.js'
import { addInfoApi } from '@/api/stocktaking/stocktakingInfo.js'
import { addLossApi } from '@/api/stocktaking/stocktakingLoss.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddStocktaking from './AddStocktaking.vue'
import ConfirmStocktaking from './ConfirmStocktaking.vue'
import ReportLoss from './ReportLoss.vue'

// 状态选项
const statusOptions = [
  { label: '未确认', value: 1 },
  { label: '已确认', value: 2 },
  { label: '已报损', value: 3 }
]

// 搜索表单
const searchForm = ref({
  title: '',
  status: '',
  category: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 控制添加盘点弹窗显示
const addStocktakingDialogVisible = ref(false)

// 控制确认盘点弹窗显示
const confirmStocktakingDialogVisible = ref(false)

// 控制报损弹窗显示
const reportLossDialogVisible = ref(false)

// 当前选中的行数据
const currentRowData = ref({})

// 弹窗组件引用
const addStocktakingRef = ref(null)
const confirmStocktakingRef = ref(null)
const reportLossRef = ref(null)

// 获取盘点列表
const fetchStocktakingList = async () => {
  loading.value = true
  try {
    const res = await getInfoPageApi(
      pagination.value.page,
      pagination.value.pageSize,
      searchForm.value.title,
      searchForm.value.status,
      searchForm.value.category=1
    )
    tableData.value = res.data.rows
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('获取盘点列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserListApi()
    userList.value = res.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 获取用户名
const getUserName = (userId) => {
  const user = userList.value.find(item => item.id == userId)
  return user ? user.name : '未知用户'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    1: '未确认',
    2: '已确认',
    3: '已报损'
  }
  return statusMap[status] || '未知状态'
}

// 获取盘点类型标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    1: '滚动盘点',
    2: '定时盘点'
  }
  return categoryMap[category] || '未知类型'
}

// 处理搜索
const handleSearch = () => {
  pagination.value.page = 1
  fetchStocktakingList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    status: ''
  }
  pagination.value.page = 1
  fetchStocktakingList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.page = page
  fetchStocktakingList()
}

// 添加盘点按钮点击事件
const handleAddStocktaking = () => {
  addStocktakingDialogVisible.value = true
}

// 关闭添加盘点弹窗
const handleCloseAddStocktaking = () => {
  addStocktakingDialogVisible.value = false
}

// 处理添加盘点确认按钮
const handleConfirmAddStocktaking = async () => {
  try {
    // 获取选中的数据
    const selectedData = addStocktakingRef.value.getSelectedData()
    
    // 检查是否有选中数据
    if (selectedData.length === 0) {
      ElMessage.warning('请至少选择一条数据')
      return
    }
    
    // 调用后端接口
    await addInfoApi(selectedData)
    
    // 关闭弹窗
    addStocktakingDialogVisible.value = false
    
    // 刷新页面数据
    fetchStocktakingList()
    
    ElMessage.success('添加盘点成功')
  } catch (error) {
    ElMessage.error('添加盘点失败: ' + error.message)
  }
}

// 确认盘点按钮点击事件
const handleConfirmStocktakingClick = (row) => {
  currentRowData.value = row
  confirmStocktakingDialogVisible.value = true
}

// 关闭确认盘点弹窗
const handleCloseConfirmStocktaking = () => {
  confirmStocktakingDialogVisible.value = false
  currentRowData.value = {}
}

// 处理确认盘点提交
const handleConfirmStocktakingSubmit = async (data) => {
  try {
    await ElMessageBox.confirm('确认要提交该盘点记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用确认接口
    await confirmApi(data)
    
    // 关闭弹窗
    handleCloseConfirmStocktaking()
    
    // 刷新列表
    fetchStocktakingList()
    
    ElMessage.success('确认盘点成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认盘点失败: ' + error.message)
    }
  }
}

// 报损按钮点击事件
const handleReportLossClick = (row) => {
  currentRowData.value = row
  reportLossDialogVisible.value = true
}

// 关闭报损弹窗
const handleCloseReportLoss = () => {
  reportLossDialogVisible.value = false
  currentRowData.value = {}
}

// 处理报损提交
const handleReportLossSubmit = async (data) => {
  try {
    await ElMessageBox.confirm('确认要提交该报损记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用报损接口
    await addLossApi(data)
    
    // 关闭弹窗
    handleCloseReportLoss()
    
    // 刷新列表
    fetchStocktakingList()
    
    ElMessage.success('报损处理成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('报损处理失败: ' + error.message)
    }
  }
}

// 删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该盘点记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用删除接口
    await deleteInfoApi(row.id)
    
    // 刷新列表
    fetchStocktakingList()
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 初始化
onMounted(() => {
  fetchStocktakingList()
  fetchUserList()
})
</script>

<template>
  <div class="stocktaking-list-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 添加盘点按钮放在最左边 -->
        <div class="left-section">
          <el-button type="primary" icon="Plus" @click="handleAddStocktaking">添加盘点</el-button>
        </div>
        
        <!-- 搜索条件放在最右边 -->
        <div class="right-section">
          <el-form-item label="商品名称">
            <el-input 
              v-model="searchForm.title" 
              placeholder="请输入商品名称" 
              clearable 
              style="width: 180px;"
            />
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable 
              style="width: 120px;"
            >
              <el-option 
                v-for="item in statusOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    
    <!-- 盘点列表表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading" 
      border 
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'warning' : scope.row.status === 2 ? 'success' : 'primary'">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="targetWarehouseName" label="仓库名称" min-width="120" />
      <el-table-column prop="targetWarehouseAreaName" label="库区名称" min-width="120" />
      <el-table-column prop="targetWarehouseLocaName" label="库位名称" min-width="120" />
      <el-table-column prop="title" label="商品名称" min-width="120" />
      <el-table-column prop="bookCount" label="账面数量" width="100" />
      <el-table-column label="盘点数量" width="100">
        <template #default="scope">
          {{ scope.row.correctCount || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="差异数量" width="100">
        <template #default="scope">
          {{ scope.row.discrepancyCount || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="盘点类型" width="100">
        <template #default="scope">
          {{ getCategoryLabel(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column label="操作员工" width="100">
        <template #default="scope">
          {{ getUserName(scope.row.empId) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleConfirmStocktakingClick(scope.row)"
            :disabled="scope.row.status !== 1"
          >
            盘点
          </el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="handleReportLossClick(scope.row)"
            :disabled="!(scope.row.status === 2 && scope.row.discrepancyCount > 0)"
          >
            报损
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status !== 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      layout="total, prev, pager, next, jumper"
      :current-page="pagination.page"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 添加盘点弹窗 -->
    <el-dialog
      v-model="addStocktakingDialogVisible"
      title="添加盘点"
      width="80%"
      @close="handleCloseAddStocktaking"
    >
      <AddStocktaking ref="addStocktakingRef" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddStocktaking">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddStocktaking">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 确认盘点弹窗 -->
    <el-dialog
      v-model="confirmStocktakingDialogVisible"
      title="确认盘点"
      width="600px"
      @close="handleCloseConfirmStocktaking"
    >
      <ConfirmStocktaking 
        ref="confirmStocktakingRef" 
        :row-data="currentRowData" 
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseConfirmStocktaking">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmStocktakingRef?.handleSubmit(handleConfirmStocktakingSubmit)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 报损弹窗 -->
    <el-dialog
      v-model="reportLossDialogVisible"
      title="报损处理"
      width="600px"
      @close="handleCloseReportLoss"
    >
      <ReportLoss 
        ref="reportLossRef" 
        :row-data="currentRowData" 
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseReportLoss">取消</el-button>
          <el-button 
            type="primary" 
            @click="reportLossRef?.handleSubmit(handleReportLossSubmit)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.stocktaking-list-container {
  padding: 20px;
  background-color: #fff;
}

.search-bar {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.left-section {
  flex-shrink: 0;
}

.right-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-end;
  flex: 1;
}
</style>